<template>
  <div>
    <a-modal :open='props.open' :width="props.modelInfo && props.modelInfo.width ? props.modelInfo.width : '900px'"
      :title="props.modelInfo && props.modelInfo.title ? props.modelInfo.title : 'Basic Modal'" @ok='handleOk'
      okText='保存' :confirmLoading='modelConfig.confirmLoading' :destroyOnClose='modelConfig.destroyOnClose'
      @cancel='handleCancel'>
      <template #footer>
        <a-button key='back' @click='handleCancel'>取消</a-button>
        <a-button key='submit' type='primary' :loading='loading' @click='handleOk'>保存</a-button>
      </template>
      <a-form ref='formRef' name='UserInfoForm' class='ant-advanced-search-form' :model='formState' @finish='onFinish'
        @finishFailed='onFinishFailed' :rules='rulesRef' :label-col='labelCol' :wrapper-col='wrapperCol'>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['code'].name" :label="labelMap['code'].label">
              <a-input v-model:value='formState.code' :placeholder="'请填写' + labelMap['code'].label"
                :disabled="true"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['phone'].name" :label="labelMap['phone'].label">
              <a-input v-model:value='formState.phone' :placeholder="'请填写' + labelMap['phone'].label"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['status'].name" :label="labelMap['status'].label">
              <a-select v-model:value="formState.status">
                <a-select-option value="1">激活</a-select-option>
                <a-select-option value="0">失效</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item :name="labelMap['self'].name" :label="labelMap['self'].label">
              <a-select v-model:value="formState.self">
                <a-select-option :value="1">是</a-select-option>
                <a-select-option :value="0">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['hiddenPhone'].name" :label="labelMap['hiddenPhone'].label">
              <a-select v-model:value="formState.hiddenPhone">
                <a-select-option :value="true">是</a-select-option>
                <a-select-option :value="false">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :span='12'>
            <a-form-item :name="labelMap['avatar'].name" :label="labelMap['avatar'].label">
              <MyUpload fromSystem="common" :fileInfo="fileInfo" @customImageRequest="customImageRequest"
                @handleRemove="handleRemove"></MyUpload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang='ts' setup>
import { UserInfoDetail } from './userInfoDetailTs';
import {
  getUserInfoDetail,
  addOrEditUserInfo,
} from '@/api/userInfo/userInfo/userInfoTs';
import { message, FormInstance } from 'ant-design-vue';
import { dictInfo } from "@/views/commonInfo/dictInfo/dictInfoListTs";
import { getDictList } from "@/api/commonInfo/dictInfo/dictInfoTs";
import { ModelInfo } from '../userInfoListTs';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let loading = ref<boolean>(false);

const formRef = ref<FormInstance>();

const labelMap = ref<any>(
  {
    username: { name: 'username', label: '用户名' },
    phone: { name: 'phone', label: '手机号码' },
    code: { name: 'code', label: '用户编码' },
    status: { name: 'status', label: '用户状态' },
    avatar: { name: 'avatar', label: '头像' },
    self: { name: 'self', label: '仅自己可见' },
    hiddenPhone: { name: 'hiddenPhone', label: '隐藏手机号' },
  });

const validatePhone = (rule, value) => {
  const phoneRegex = /^1[3-9]\d{9}$/; // Regular expression for valid Chinese phone number
  if (!value) {
    return Promise.reject('请输入手机号');
  }
  if (!phoneRegex.test(value)) {
    return Promise.reject('手机号格式不正确');
  }
  return Promise.resolve();
}

const rulesRef = reactive({
  password: [
    {
      required: true,
      message: '密码（加密存储）不能为空！',
    },
  ],
  phone: [
    {
      required: true,
      message: '手机号码不能为空！',
    },
    {
      validator: validatePhone,
      trigger: 'change',
    },
  ],
  status: [
    {
      required: true,
      message: '用户状态不能为空！',
    },
  ],
  wechatOpenid: [
    {
      required: true,
      message: '微信OpenID不能为空！',
    },
  ],
  wechatUnionid: [
    {
      required: true,
      message: '微信UnionID（跨平台统一标识）不能为空！',
    },
  ],
  wechatBindTime: [
    {
      required: true,
      message: '绑定微信账号的时间不能为空！',
    },
  ],
  introUserId: [
    {
      required: true,
      message: '推荐人id不能为空！',
    },
  ],
  codeNum: [
    {
      required: true,
      message: 'code数不能为空！',
    },
  ],
  source: [
    {
      required: true,
      message: '来源不能为空！',
    },
  ],
});

const modelConfig = {
  confirmLoading: true,
  destroyOnClose: true,
};

interface Props {
  open?: boolean;
  modelInfo?: ModelInfo;
}
const props = defineProps<Props>();

let formState = ref<UserInfoDetail>({});

let sourceList = ref<dictInfo[]>([]);

const getDictInfoList = () => {
  getDictList("source").then((res) => {
    if (res.code == "200") {
      sourceList.value = res.data.filter(
        (item: { belongTo: string }) => item.belongTo == "source"
      );
    } else {
      message.error((res && res.message) || "查询列表失败！");
    }
  });
}

const emit = defineEmits(['handleOk', 'handleCancel']);

const handleOk = (): void => {
  loading.value = true;
  if (formRef.value) {
    formRef.value.validateFields().then(
      () => saveUserInfoManager()).catch(() => {
        loading.value = false;
      });
  }
};

const handleCancel = (): void => {
  emit('handleCancel', false);
};

const customImageRequest = (file: any) => {
  formState.value.avatar = file.id;
}

const handleRemove = () => {
  formState.value.avatar = null;
}

//保存用户信息信息
const saveUserInfoManager = (): void => {
  let method = '';
  if (formState.value.id) {
    method = 'put';
  } else {
    method = 'post';
  }
  addOrEditUserInfo(method, formState.value)
    .then((res) => {
      if (res.code == '200') {
        message.success((res && res.message) || '保存成功！');
        emit('handleOk', false);
      } else {
        message.error((res && res.message) || '保存失败！');
      }
      formState.value = {};
    })
    .catch((error: any) => {
      message.error((error?.message) || '保存失败！');
    }).finally(() => {
      loading.value = false;
    });
}

const onFinish = (values: any): void => {
  console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any): void => {
  console.log('Failed:', errorInfo);
};

let fileInfo = ref<any>(null);

const init = (): void => {
  getDictInfoList();
  if (props.modelInfo) {
    if (props.modelInfo.id) {
      getUserInfoDetail(props.modelInfo.id)
        .then((res) => {
          if (res.code == '200') {
            formState.value = res.data;
            modelConfig.confirmLoading = false;
            fileInfo.value = {
              id: res.data?.avatar,
              url: res.data?.personAvatar?.preUrl || '',
            };
            if (!formState.value?.self) {
              formState.value.self = 0;
            }
            if (!formState.value?.hiddenPhone) {
              formState.value.hiddenPhone = false;
            }
          } else {
            message.error((res && res.message) || '查询失败！');
          }
        })
        .catch((error: any) => {
          let data = error?.response?.data;
          if (data) {
            message.error((data?.message) || '查询失败！');
          }
        });
    } else {
      modelConfig.confirmLoading = false;
      formState.value = {
        source: 1,
        self: 0,
        status: '1',
        hiddenPhone: false,
      };
    }
  }
}

watch(
  () => props.open,
  (newVal) => {
    if (newVal) {
      init();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

defineExpose({ handleOk, handleCancel });
</script>
<style lang='scss' scoped></style>